/**
 * 
 */
package com.pengtu.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pengtu.Constants;
import com.pengtu.entity.app.Attachment;
import com.pengtu.utils.web.ServletUtils;

/**
 * @author 631wj
 * 
 */
public class UploadFile {

	private static Log log = LogFactory.getLog(UploadFile.class);

	
	/**
	 * 删除文件
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws IOException
	 */
	public static boolean deleteFile(HttpServletRequest request,Attachment attachment)
	throws IOException {
		return deleteFile(getAppRootPath(request), attachment);
	}
	
	/**
	 * 删除文件
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws IOException
	 */
	public static boolean deleteFile(String rootPath,Attachment attachment)
	throws IOException {
		// 得到文件的存储实际全路径
		StringBuffer filePath = new StringBuffer();
		filePath.append(rootPath).append(
				attachment.getFullPath());
		File file = new File(filePath.toString());
			// 文件已经不存在
		  if(!file.isFile()){
			  return  true;
		  }
		  else{
			  return file.delete();
		  }
		
	}
	

	/**
	 * 下载文件
	 * 
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws IOException
	 */
	public static boolean downloadFile(HttpServletRequest request,
			HttpServletResponse response, Attachment attachment)
			throws IOException {
		InputStream fileInput = null;
		OutputStream filetoClient = null;
		try {
			// 得到文件的存储实际全路径
			StringBuffer filePath = new StringBuffer();
			filePath.append(getAppRootPath(request)).append(
					attachment.getFullPath());
			// 判断文件是否存在
			File file = new File(filePath.toString());
			// 文件类型
			String upfileContentType = attachment.getUpfileContentType();
			// 下载的文件名
			StringBuffer downloadFileName = new StringBuffer();
			if (!file.isFile()) {
				file = new File(getAppRootPath(request)
						+ Constants.CANNOT_FOUND_FILE_PATH);
				upfileContentType = ServletUtils.IMAGE_TYPE;
				downloadFileName.append("文件不存在.gif");
			} else {
				// 设置下载的文件名
				if (StringUtils.isEmpty(attachment.getFileName()))
					// 这是上传时的文件名
					downloadFileName.append(attachment.getUpfileFileName());
				else {
					// 这是以用户填写的文件名作为下载
					downloadFileName.append(attachment.getFileName());
					downloadFileName.append(".").append(
							getFileExtension(attachment.getUpfileFileName()));
				}
				// 流的形式
				if (StringUtils.isEmpty(upfileContentType)) {
					upfileContentType = ServletUtils.STREAM_TYPE;
				}
			}
			// 设置文件下载头
			ServletUtils.setFileDownloadHeader(response, downloadFileName.toString());
			response.setContentType(upfileContentType);
			// 文件输入流
			fileInput = new BufferedInputStream(new FileInputStream(file));
			// 输出流
			filetoClient = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[4096];
			int len = 0;
			// 写入输出流
			while ((len = fileInput.read(buffer, 0, buffer.length)) != -1) {
				filetoClient.write(buffer, 0, len);
			}
		} catch (IOException e) {
			log.error("can not download", e);
			return false;
		} finally {
			try {
				if (fileInput != null) {
					fileInput.close();
				}
				fileInput = null;

				if (filetoClient != null) {
					filetoClient.close();
				}
				filetoClient = null;
			} catch (IOException e) {
				log.error("can not download", e);
				return false;
			}
		}

		return true;

	}

	/**
	 * 查看图片
	 * 
	 * @param request
	 * @param response
	 * @param attachment
	 * @return
	 * @throws IOException
	 */
	public static boolean downloadImageFile(HttpServletRequest request,
			HttpServletResponse response, Attachment attachment)
			throws IOException {
		InputStream fileInput = null;
		OutputStream filetoClient = null;
		try {
			// 设置下载的文件名
			StringBuffer downloadFileName = new StringBuffer();
			if (StringUtils.isEmpty(attachment.getFileName()))
				// 这是上传时的文件名
				downloadFileName.append(attachment.getUpfileFileName());
			else {
				// 这是以用户填写的文件名作为下载
				downloadFileName.append(attachment.getFileName());
				downloadFileName.append(".").append(
						getFileExtension(attachment.getUpfileFileName()));
			}

			response.reset();
			// 设置文件下载头
			response.setHeader("Content-Disposition", "inline; filename=\""
					+ URLEncoder.encode(downloadFileName.toString(), "UTF-8")
					+ "\"");
			response.setContentType(ServletUtils.IMAGE_TYPE);
			// 得到文件的存储实际全路径
			StringBuffer filePath = new StringBuffer();
			filePath.append(getAppRootPath(request)).append(
					attachment.getFullPath());
			File imageFile = new File(filePath.toString());
			  if(!imageFile.isFile()){
				  imageFile =  new File(getAppRootPath(request)+Constants.CANNOT_FOUND_IMAGE_PATH);  
			  }
			// 文件输入流
			  try {
			    fileInput = new BufferedInputStream(new FileInputStream(imageFile));
			} catch (Exception e) {
				
			}
			// 输出流
			filetoClient = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[4096];
			int len = 0;
			// 写入输出流
			while ((len = fileInput.read(buffer, 0, buffer.length)) != -1) {
				filetoClient.write(buffer, 0, len);
			}
		} catch (IOException e) {
			log.error("can not download", e);
			return false;
		} finally {
			try {
				if (fileInput != null) {
					fileInput.close();
				}
				fileInput = null;

				if (filetoClient != null) {
					filetoClient.close();
				}
				filetoClient = null;
			} catch (IOException e) {
				log.error("can not download", e);
				return false;
			}
		}

		return true;

	}
	
	/**
	 * 下载模版导出excel文件
	 * downloadFileByInputStream:
	 * 适用:  要与  ExcelHelper.createWritableWorkbook(OutputStream out,String templatePath) 配合使用
	 * @param filetoClient
	 * @param response
	 * @param fileName
	 * @return
	 * @throws IOException 
	 * @exception 
	 * @since  1.0.0
	 */
	public static boolean downloadExcelFile(WritableWorkbook wwb ,HttpServletResponse response, String fileName) throws IOException {
		OutputStream filetoClient = null;
			try {
				ServletUtils.setFileDownloadHeader(response, fileName);
				response.setContentType(ServletUtils.EXCEL_TYPE);
				filetoClient = response.getOutputStream();
			} catch (IOException e) {
				log.error("can not download");
				//e.printStackTrace();
				response.sendError(405, "File cannot found!");
				return false;
			} finally {
				try {
					wwb.write();
					wwb.close();
				} catch (WriteException e1) {
					log.error("can not download"+e1);
					response.sendError(405, "download error!");
				}
				try {
					if (filetoClient != null) {
						filetoClient.flush();
						filetoClient.close();
					}
					filetoClient =null;
				} catch (IOException e) {
					log.error("can not download");
					//e.printStackTrace();
					response.sendError(405, "download error!");
					return false;
				} 
			}
			return true;
	}
	
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static boolean downloadFileByInputStream(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
		if (file!=null) {
			InputStream fileInput = null;
			OutputStream filetoClient = null;
			try {
				if (!file.isFile()) {
					file = new File(getAppRootPath(request)
							+ Constants.CANNOT_FOUND_FILE_PATH);
					response.setContentType(ServletUtils.IMAGE_TYPE);
				} 
				ServletUtils.setFileDownloadHeader(response, file.getName());
				fileInput = new FileInputStream(file);
				filetoClient = response.getOutputStream();
				byte[] buffer = new byte[1024*8];
				int len=0;
				// 写入输出流
				while((len = fileInput.read(buffer)) != -1){
					filetoClient.write(buffer, 0, len);	
				}
				filetoClient.flush();
			} catch (IOException e) {
				log.error("can not download");
				//e.printStackTrace();
				response.sendError(405, "File cannot found!");
				return false;
			} finally {
				try {
					if (fileInput != null) {
						fileInput.close();
					}
					fileInput = null;
					if (filetoClient != null) {
						filetoClient.close();
					}
					filetoClient =null;
				} catch (IOException e) {
					log.error("can not download");
					//e.printStackTrace();
					response.sendError(405, "download error!");
					return false;
				} 
			}
			return true;
		} else {
			log.error(" file is null");
			response.sendError(405, "File cannot found!");
			return false;
		}
	}
	
	

	/**
	 * 将文件存入服务器指定文件夹
	 * 
	 * @param item
	 *            file信息
	 * @param rootPath
	 *            根目录
	 * @return filePath 文件的路径/除根目录
	 * @throws FileCannotUploadException
	 */
	public static void processUploadedFile(String rootPath,Attachment attachment) throws FileCannotUploadException {
		File upFile = attachment.getUpfile();
		// 得到文件后缀名
		String fileExtension = getFileExtension(attachment.getUpfileFileName());
		// 产生随机数
		Random random = new Random();
		// 设置文件全路径
		StringBuilder fileNameBuffer = new StringBuilder();
		
		fileNameBuffer.append(Constants.UPLOAD_PATH).append(attachment.getTableName()).append(
				Constants.FILE_SEP).append(attachment.getTableField()).append(
						Constants.FILE_SEP).append(attachment.getType()).append(
								Constants.FILE_SEP);
		StringBuilder filePath  = new StringBuilder();
		filePath.append(System.currentTimeMillis()).append(random.nextLong()).append(".").append(fileExtension);
		fileNameBuffer.append(filePath);
		String fullPath = fileNameBuffer.toString();
		File uploadedFile = new File(rootPath, fullPath);
		FileUtils.makeDirectory(uploadedFile);
		FileUtils.copy(upFile, uploadedFile,Boolean.TRUE);
		attachment.setPath(filePath.toString());
		attachment.setFullPath(fullPath);
	}
	
	
	/**
	 * 得到根目录
	 * 
	 * @param request
	 * @return
	 */
	public static String getAppRootPath(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		StringBuffer rootPath = new StringBuffer();
		rootPath.append(session.getServletContext().getRealPath("/"));
		return rootPath.toString();
	}
	

	/**判断不允许上传的格式*/ 
	
	public static boolean islegality(String fileName){
	  String fileExt = getFileExtension(fileName);
	  fileExt = fileExt.toLowerCase();
	  if(fileExt.endsWith("exe") || fileExt.endsWith("bat") || fileExt.endsWith("jsp") || fileExt.endsWith("class") || fileExt.endsWith("dll") || fileExt.endsWith("msi") || fileExt.endsWith("com") || fileExt.endsWith("sys") || fileExt.endsWith("jar")){
		  
		  return false;
	  }
	  return true;
	}
	/**
	 * 得到上传文件的后缀名
	 * 
	 * @param item
	 * @return
	 */
	public static String getFileExtension(File file) {
		String fileName = file.getName();
		String extension = "";
		if (fileName != null) {
			extension = FilenameUtils.getExtension(fileName);
		}
		return extension;

	}

	/**
	 * 得到上传文件的后缀名
	 * 
	 * @param item
	 * @return
	 */
	public static String getFileExtension(String fileName) {
		String extension = "";
		if (fileName != null) {
			extension = FilenameUtils.getExtension(fileName);
		}
		return extension;

	}
}